﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace LxCFD
{
    public class LxTool
    {
        public static readonly double OneThird = 1 / 3.0;
        public static readonly double TwoThird = 2 / 3.0;


        //要复制的实例必须可序列化，包括实例引用的其它实例都必须在类定义时加[Serializable]特性。
        public static T Copy<T>(T RealObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制 
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, RealObject);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }
        }

        public static void CheckCreateArray<T>(ref T[] Array, int count)
        {
            if (Array == null || Array.Length != count)
            {
                Array = new T[count];
            }
        }
        public static void CheckCreateInstance<TSpecific, TBase>(ref TBase valueNow) where TSpecific : class, TBase, new()
        {
            if (valueNow == null || valueNow.GetType() != typeof(TSpecific))
            {
                valueNow = new TSpecific();
            }
        }
        public static void Exchange<T>(ref T a, ref T b)
        {
            T temp = a;
            a = b;
            b = temp;
        }
        public static double RoundOff(double d, int bit)
        {
            return double.Parse(d.ToString($"N{bit}"));
        }
    }
}

//public static void IfArrayNullCreate(ref double[] Array, int count)
//{
//    if (Array == null || Array.Length != count)
//    {
//        Array = new double[count];
//    }
//}